package com.ssy.lingxi.member.merchant.utils;

import com.ssy.lingxi.member.merchant.entity.MemberOrganizationDO;
import com.ssy.lingxi.member.merchant.model.bo.MemberOrgTreeBO;
import com.ssy.lingxi.member.merchant.model.vo.maintenance.response.MemberOrgTreeVO;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 会员组织机构工具类
 * @author 万宁
 * @version 2.0.0
 * @date 2021-04-02
 */
public class MemberOrganizationUtil implements Serializable {
    private static final long serialVersionUID = -5694948275018281573L;

    private static final List<MemberOrgTreeBO> EMPTY_LIST = new ArrayList<>();

    public static List<MemberOrgTreeVO> transferToTree(List<MemberOrganizationDO> organizationDOList) {
        if(CollectionUtils.isEmpty(organizationDOList)) {
            return new ArrayList<>();
        }

        List<MemberOrgTreeVO> resultList = new ArrayList<>();

        //取最大层级
        int maxLevel = organizationDOList.stream().mapToInt(MemberOrganizationDO::getLevel).max().orElse(0);

        //由于List<T>的子List操作是引用，所以可以用下面的方法
        //用于记录上一次操作的节点（上一次操作的节点全部为叶子节点）
        List<MemberOrgTreeVO> leafList = new ArrayList<>();

        //循环每个菜单的层级，并排序，构建整个菜单树
        for (int level=1; level<=maxLevel; level++) {
            List<MemberOrgTreeVO> lastList = new ArrayList<>();
            int finalLevel = level;
            if( finalLevel == 1) {
                resultList = organizationDOList.stream().filter(c -> c.getLevel() == finalLevel).sorted(Comparator.comparingLong(MemberOrganizationDO::getId)).map(c -> new MemberOrgTreeVO(c.getId(), c.getTitle(), null)).collect(Collectors.toList());
                leafList = resultList;
            } else {
                List<MemberOrganizationDO> subList = organizationDOList.stream().filter(c -> c.getLevel() == finalLevel).collect(Collectors.toList());
                for (MemberOrgTreeVO treeLeaf: leafList) {
                    List<MemberOrgTreeVO> tmpList = subList.stream().filter(c -> c.getParentId().equals(treeLeaf.getId())).sorted(Comparator.comparingLong(MemberOrganizationDO::getId)).map(c -> new MemberOrgTreeVO(c.getId(), c.getTitle(),null)).collect(Collectors.toList());
                    treeLeaf.setChildren(tmpList);
                    if(!CollectionUtils.isEmpty(tmpList)) {
                        lastList.addAll(tmpList);
                    }
                }
                leafList = lastList;
            }
        }

        return resultList;
    }

    /**
     * 将上级组织机构的名称，至当前的组织机构的名称，拼接为字符串
     * @param orgId 当前的组织机构Id
     * @param orgList 会员组织机构列表
     * @return 字符串
     */
    public static String joinTitleToString(Long orgId, List<MemberOrganizationDO> orgList) {
        if(NumberUtil.isNullOrZero(orgId) || CollectionUtils.isEmpty(orgList)) {
            return "";
        }

        MemberOrganizationDO organizationDO = orgList.stream().filter(org -> org.getId().equals(orgId)).findFirst().orElse(null);
        if(organizationDO == null) {
            return "";
        }

        List<String> nameList = new ArrayList<>();
        //添加当前的名称
        nameList.add(organizationDO.getTitle());

        //递归
        recurseTitleToString(nameList, organizationDO, orgList);

        return String.join("--", nameList);
    }

    /**
     * 递归拼接上级组织机构至当前组织机构的名称
     * @param nameList  名称列表
     * @param organizationDO 当前的组织机构
     * @param orgList 组织机构列表
     */
    private static void recurseTitleToString(List<String> nameList, MemberOrganizationDO organizationDO, List<MemberOrganizationDO> orgList) {
        if(organizationDO.getParentId().equals(0L)) {
            return;
        }

        MemberOrganizationDO parentOrg = orgList.stream().filter(org -> org.getId().equals(organizationDO.getParentId())).findFirst().orElse(null);
        if(parentOrg == null) {
            return;
        }

        nameList.add(0, parentOrg.getTitle());

        recurseTitleToString(nameList, parentOrg, orgList);
    }

    /**
     * 递归获取门店信息，并将门店id统计到storeIds中
     * @param orgList  当前会员的所有组织信息
     * @param orgId    当前parentId
     * @param storeIds 门店id列表
     */
    public static List<MemberOrgTreeBO> buildOrgTree(List<MemberOrgTreeBO> orgList, long orgId, List<Long> storeIds) {
        return buildOrgTree(orgList.stream().collect(Collectors.groupingBy(MemberOrgTreeBO::getParentId)), orgId, storeIds);
    }

    /**
     * 递归获取门店信息，并将门店id统计到storeIds中
     * @param orgMap   当前会员的组织信息，按parentId做聚类，key为parentId
     * @param parentId 当前parentId
     * @param storeIds 门店id列表
     */
    public static List<MemberOrgTreeBO> buildOrgTree(Map<Long, List<MemberOrgTreeBO>> orgMap, long parentId, List<Long> storeIds) {
        if (orgMap.containsKey(parentId)) {
            List<MemberOrgTreeBO> currentOrgList = orgMap.get(parentId);
            for (MemberOrgTreeBO orgTreeBO : currentOrgList) {
                if (orgTreeBO.getStoreId() != null) {
                    storeIds.add(orgTreeBO.getStoreId());
                }
                List<MemberOrgTreeBO> childOrgTreeList = buildOrgTree(orgMap, orgTreeBO.getId(), storeIds);
                if (orgTreeBO.getChild() == null) {
                    orgTreeBO.setChild(new ArrayList<>());
                }
                orgTreeBO.getChild().addAll(childOrgTreeList);
            }
            return currentOrgList;
        }
        return EMPTY_LIST;
    }
}
